import { rspc } from '@fill/client';
import { Space, Typography } from 'antd';
import dayjs from 'dayjs';
import { keyBy } from 'lodash';
import React, { useContext, useEffect, useState } from 'react';
import { CONFIG_KEYS } from '../../constants/config';
import type { NODE_TYPE } from '../../constants/default';
import { TIMEOUT_ENUM } from '../../constants/default';
import { FillContext } from '../app/Fill';

export interface IStatusProps {
  module: NODE_TYPE
}

export const Status: React.FC<IStatusProps> = ({
  module,
}) => {
  const { config } = useContext(FillContext);
  const [status, setStatus] = useState(true);

  const { data } = rspc.useQuery(['records.latest', {
    arg: {
      module,
    },
  }]);

  useEffect(() => {
    if (Array.isArray(data) && data.length) {
      let latest = dayjs(+data[0].created_at);
      const timeout = keyBy(JSON.parse(config[CONFIG_KEYS.TIMEOUT][0].F_YJPZ_), 'yjType');
      const current = timeout[module];
      console.log(String(current.yjMs), current.yjSj);
      switch (String(current.yjMs)) {
        case TIMEOUT_ENUM.DAY:
          latest = latest.add(+current.yjSj, 'day');
          break;

        case TIMEOUT_ENUM.WEEK:
          latest = latest.add(+current.yjSj, 'week');
          break;

        case TIMEOUT_ENUM.MONTH:
          latest = latest.add(+current.yjSj, 'month');
          break;
      }

      setStatus(latest.isAfter(dayjs()));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data, config]);

  return (
    <Space>
      <Typography.Text>整改报告状态:</Typography.Text>
      {
        status
          ? <Typography.Text type="success">未超期</Typography.Text>
          : <Typography.Text type="danger">超期</Typography.Text>
      }
    </Space>
  );
};
